<template>
  <div class="options-panel">
    <vue-draggable-next :list="labels" @change="emitModelValue">
      <el-row v-for="(label, index) in labels" :key="label" class="mr-3">
        <el-tag closable :disable-transitions="false" @close="handleClose(index)">
          <el-icon><i-ep-grid /></el-icon><span class="tag-line">{{ label }}</span>
        </el-tag>
      </el-row>
    </vue-draggable-next>
    <el-row>
      <el-input
        v-if="inputVisible"
        ref="InputRef"
        v-model="inputValue"
        class="ml-1 w-20"
        size="small"
        @keyup.enter="handleInputConfirm2"
        @blur="handleInputConfirm"
      />
      <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
        <el-icon><i-ep-plus /></el-icon>
      </el-button>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
  import { VueDraggableNext } from 'vue-draggable-next';
  import { nextTick, ref } from 'vue';
  import { ElInput } from 'element-plus';
  import { SelectorOption, SelectorOptions } from '../form';

  const props = defineProps<{
    modelValue?: SelectorOptions;
  }>();

  const emit = defineEmits<{
    (e: 'update:modelValue', v: SelectorOptions): void;
  }>();

  const labels = ref<Array<string | number>>(
    props.modelValue?.map((v: SelectorOption) => v.label) || []
  );

  const emitModelValue = () =>
    emit(
      'update:modelValue',
      labels.value.map((v, i) => ({
        label: v,
        value: i
      }))
    );

  const inputValue = ref('');
  const inputVisible = ref(false);
  const InputRef = ref<InstanceType<typeof ElInput>>();

  const handleClose = (index: number) => {
    labels.value.splice(index, 1);
    emitModelValue();
  };

  const showInput = () => {
    inputVisible.value = true;
    nextTick(() => {
      InputRef.value?.input?.focus();
    });
  };

  const handleInputConfirm = () => {
    if (inputValue.value) {
      labels.value.push(inputValue.value);
      emitModelValue();
    }
    inputVisible.value = false;
    inputValue.value = '';
  };

  const handleInputConfirm2 = () => {
    handleInputConfirm();
    showInput();
  };
</script>

<style scoped>
  .options-panel {
    width: 100%;
  }
  .mr-3 {
    margin-bottom: 3px;
  }

  .tag-line {
    width: 100%;
  }
</style>
